﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wwtfly.BBS.BackControllers.Home;
using System.Web.Mvc;
using Wwtfly.BBS.BackControllers.Attributes;
using Wwtfly.BBS.Enums.Common;
using Wwtfly.BBS.BackModels.ViewModels.News;
using Wwtfly.BBS.BackModels.Models.News;
using Wwtfly.BBS.BackBLL.News;
using Wwtfly.BBS.Framework.Common;
using Wwtfly.Utility;
using System.Web;
using Wwtfly.LoggerUtility;
using Wwtfly.BBS.BackModels;
using Wwtfly.BBS.BackModels.Models.Common;

namespace Wwtfly.BBS.BackControllers.News
{

    /// <summary>
    /// 新闻 控件器
    /// </summary>
    [HasFolder("Back")] 
    public class BackNewsController : BackBaseController
    {

        /// <summary>
        /// 分页大小 
        /// </summary>
        private static readonly int PageSize = 15;


        // 获取列表页
        [HasPower(PowerTypeEnum.Browse)]
        public ActionResult Index(string pageParams)
        {
            ViewData["Title"] = "新闻列表页";
            PageParams pp = !string.IsNullOrEmpty(pageParams) ? new PageParams(pageParams) :
                new PageParams() { PageIndex = 1, PageSize = PageSize };
            NewsShowsSearchModel search = this.RestoreSearch<NewsShowsSearchModel>(null);
            NewsShowsViewModel viewModel = new NewsShowsViewModel()
            {
                PageParams = pp,
                NewsShowsPagedList = NewsBLL.GetNewsShowsPageList(pp, search),
                NewsShowsSearch = search ?? new NewsShowsSearchModel(),
                NewTypesList = new SelectList(NewTypesBLL.GetNewsTypesList("0"), "Id", "Title")
            };
            return View(viewModel);
        }

        // 搜索
        [HttpPost]
        [HasPower(PowerTypeEnum.Browse)]
        public ActionResult Search(NewsShowsViewModel viewModel)
        {
            this.SaveSearch(viewModel.NewsShowsSearch, null);
            return RedirectToAction("Index");
        }

        //重置 搜索..
        public ActionResult SearchReset()
        {
            this.ResetSearch(null);
            return RedirectToAction("Index");
        }

        // 删除
        [HasPower(PowerTypeEnum.Delete)]
        public ActionResult Delete(string id)
        {
            try
            {
                bool b = NewsBLL.Delete(id.AsInt(0));
                if (b)
                {
                    return this.Json(
                        new
                    JsonResultModel
                    {
                        ResultCode = "100",
                        ResultMessage = null
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                LoggerManage.Error(new LogMessageParams()
                {
                    ModuleID = "BackNewsController.cs",
                    FuncCode = "Delete(string id)",
                    Level = AppErrorLevel.EROR,
                    ErrCode = "0x0",
                    Excep = ex,
                    logMessage = "删除(新闻).出错",
                    ProgramName = "Wwtilfy.BBS"
                });
            }

            return this.Json(new
            JsonResultModel
            {
                ResultCode = "-100",
                ResultMessage = string.Format("删除失败!")
            }, JsonRequestBehavior.AllowGet);
        }

        //浏览
         [HasPower(PowerTypeEnum.Browse)]
        public ActionResult Details(string id)
        {
            
            return RedirectToAction("Index");
        }
        
        //
        [HttpPost, HasPower(PowerTypeEnum.Delete)]
        public ActionResult Deletes()
        {
            return View();
        }

        // 添加
        [HasPower(PowerTypeEnum.Add)]
        [ValidateInput(false)]
        public ActionResult Add(string id)
        {
            ViewData["Title"] = "添加";
            return Edit(id);
        }

        // 添加
        [HttpPost, HasPower(PowerTypeEnum.Add)]
        [ValidateInput(false)]
        public ActionResult Add(NewsShowsViewModel viewModel)
        {
            return EditSave(viewModel);

        }
        // 编辑
        [HasPower(PowerTypeEnum.Edit)]
        [ValidateInput(false)]
        public ActionResult Update(string id)
        {
            ViewData["Title"] = "修改";
            return Edit(id);
        }


        [HttpPost, HasPower(PowerTypeEnum.Edit)]
        [ValidateInput(false)]
        public ActionResult Update(NewsShowsViewModel viewModel)
        {
            return EditSave(viewModel);
        }


        #region Override 重写

        protected override string RightCode
        {
            get
            {
                return "BackBBS_NewsShows";
            }
        }

        #endregion


        #region Private Methods

        /// <summary>
        /// 返回 新增,编辑 界面
        /// </summary>
        /// <returns></returns>
        private ActionResult Edit(string id)
        {
            NewsShowsViewModel viewModel = new NewsShowsViewModel()
            {
                NewsShows = NewsBLL.GetInfo(id.AsInt(0)),
            };
            viewModel.NewTypesList = new SelectList(
                NewTypesBLL.GetNewsTypesList("0"),
               "Id", "Title", viewModel.NewsShows.TypeId.ToString());
            return View("Edit", viewModel);
        }

  
        /// <summary>
        /// 编辑保存
        /// </summary>
        /// <returns></returns>
        private ActionResult EditSave(NewsShowsViewModel viewModel)
        {

            //验证...
            List<string> errMessageList = this.ValidateData(viewModel);
            if (errMessageList != null && errMessageList.Count > 0)
            {
                ErrorViewModel errorViewModel = new ErrorViewModel()
                {
                    InfoList = errMessageList
                };
                return this.ErrorResult(errorViewModel);
            }

            try
            {
                if (viewModel.NewsShows.Id <= 0)
                {
                    viewModel.NewsShows.CreateTime = DateTime.Now;
                    viewModel.NewsShows.CreateUser = User.UserInfo.Id;
                    viewModel.NewsShows.LastModifyTime = DateTime.Now;
                    viewModel.NewsShows.LastModifyUser = User.UserInfo.Id;

                    NewsBLL.Add(viewModel.NewsShows);
                }
                else
                {
                    NewsShowsModel model = NewsBLL.GetInfo(viewModel.NewsShows.Id);
                    model.TypeId = viewModel.NewsShows.TypeId;
                    model.Keyword = viewModel.NewsShows.Keyword;
                    model.NewsTitle = viewModel.NewsShows.NewsTitle;
                    model.NewsContent = viewModel.NewsShows.NewsContent;
                    model.NewsInTime = viewModel.NewsShows.NewsInTime;
                    model.NewsClick = viewModel.NewsShows.NewsClick;
                    model.NewsTag = viewModel.NewsShows.NewsTag;
                    model.NewsState = viewModel.NewsShows.NewsState;
                    model.NewsRemark = viewModel.NewsShows.NewsRemark;
                    model.LastModifyTime = DateTime.Now;
                    model.LastModifyUser = User.UserInfo.Id;
                    NewsBLL.Update(model);
                }
                return this.Json(new
                {
                    result = "100",
                    html = string.Format("{0}", "保存成功!")
                });
            }
            catch (Exception ex)
            {
                LoggerManage.Error(new LogMessageParams()
                {
                    ModuleID = "BackNewsController.cs",
                    FuncCode = "EditSave(NewsShowsViewModel viewModel)",
                    Level = AppErrorLevel.EROR,
                    ErrCode = "0x0",
                    Excep = ex,
                    logMessage = "编辑保存model(新闻).出错",
                    ProgramName = "Wwtilfy.BBS"
                });
            }

            return this.Json(new
            {
                result = "-100",
                title = "警告信息",
                html = string.Format("请尝试刷新页面或联系管理员.")
            });
        }

        /// <summary>
        /// 验证 相关...
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        private List<string> ValidateData(NewsShowsViewModel viewModel)
        {

            List<string> errMessageList = new List<string>();
            if (string.IsNullOrEmpty(viewModel.NewsShows.NewsTitle))
            {
                errMessageList.Add("新闻标题不能为空!");
            }
            return errMessageList;
        }

        #endregion
    }
}
